// 读取环境变量
require("dotenv").config();
// 初始化数据库连接 
const { db } = require("./database");

const { PORT = 3333 } = process.env;
// 导入 express 包
const express = require("express");
// 异步错误捕获补丁
require("express-async-errors");
// 生成 express 服务实例 Application extends Router
const app = express();

// 使用 cors 中间件支持跨域资源共享
const cors = require("cors");
app.use(
  cors({
    origin: (origin, callback) => {
      callback(null, origin);
    },
    credentials: true,
  })
);

// 使用中间件解析 body
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// session 中间件
const session = require("express-session");
// 信任反向代理
app.set("trust proxy", 1);
app.use(
  session({
    secret: "switch a good secret key",
    resave: true,
    saveUninitialized: true,
    cookie: {
      secure: false,
      httpOnly: false,
      maxAge: 30 * 60 * 1000,
    },
  })
);

// 使用中间件静态文件服务
app.use(express.static("public"));

// 注册路由
const fs = require("fs");
fs.readdirSync(__dirname + "/routers").forEach((file) => {
  try {
    const module = require(`./routers/${file}`);
    if (module.registerRouter) module.registerRouter(app);
  } catch (error) {
    console.log(error);
  }
});
//
// const userRouter = require("./routers/user");
// userRouter.registerRouter(app);
// const todoRouter = require("./routers/todos");
// todoRouter.registerRouter(app);

// 全局错误处理
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).send({ success: false, message: err.message });
});
// 启动服务监听
app.listen(PORT, () => {
  console.log(`Web服务成功启动：http://localhost:${PORT}`);
});
process.on("SIGINT", async () => {
  await db.close();
  console.log("database closed ...");
  process.exit();
});
